package com.example.lt.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.example.lt.authority.Authority;
import com.example.lt.entity.dto.AssignRoleDTO;
import com.example.lt.entity.dto.AuthorityDTO;
import com.example.lt.entity.queryPage.BasePage;
import com.example.lt.entity.user.Role;
import com.example.lt.entity.user.RolePermission;
import com.example.lt.entity.user.Tree;
import com.example.lt.entity.user.UserRole;
import com.example.lt.service.user.RolePermissionService;
import com.example.lt.service.user.RoleService;
import com.example.lt.service.user.UserRoleService;
import com.example.lt.util.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author 小涛Tao
 * @Date: 2024/08/20/18:24
 * version 1.0 注释：管理端角色控制器
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/authorize/role")
public class RoleController {

    private final RoleService roleService;

    private final UserRoleService userRoleService;

    private final RolePermissionService rolePermissionService;


    /**
     * 获取权限，树形结构
     * @return
     */
    @GetMapping("/treeList")
    public List<Tree> treeList() {
        log.info("获取权限，树形结构");
        List<Tree> data = roleService.tree();
        return data;
    }

    /**
     * 为用户分配角色接口
     * @param assignRoleDTO 用户id，角色id集合
     * @return
     */
    @PostMapping("/assignRole")
    public Result assignRole(@RequestBody AssignRoleDTO assignRoleDTO) {
        log.info("为用户：{} 分配角色：{}", assignRoleDTO.getUId(), assignRoleDTO.getRId());
        return roleService.gaveRole(assignRoleDTO);
    }

    /**
     * 获取用户所拥有的角色，根据 userId 去用户角色表中查询
     * @param userId
     * @return
     */
    @GetMapping("/getUserRole/{userId}")
    public List getRole(@PathVariable Integer userId) {
        log.info("获取用户：{}拥有的角色", userId);
        List<Long> list = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId).select(UserRole::getRoleId))
                .stream().map(UserRole::getRoleId).collect(Collectors.toList());
        return list;
    }


    /**
     * 初始化角色，把角色的id和名称对应起来
     * @return
     */
    @GetMapping("/initRole")
    public List<Map<String, Object>> initRole() {
        log.info("初始化角色，把角色的id和名称对应起来");
        List<Map<String, Object>> list = roleService.list(null).stream()
                .map(role -> {
                    Map<String, Object> data = new HashMap<>();
                    data.put("value", role.getId());
                    data.put("title", role.getName());
                    return data;
                }).collect(Collectors.toList());
        return list;
    }


    /**
     * 查询角色列表
     * @param basePage
     * @param name
     * @return
     */
    @GetMapping("/list")
    public Result list(BasePage basePage, @RequestParam(required = false) String name) {
        log.info("查询角色列表");
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!ObjectUtils.isEmpty(name), Role::getName, name);
        IPage iPage = basePage.page();
        IPage page = roleService.page(iPage, wrapper);
        return Result.ok().data(page.getRecords()).count(page.getRecords().size());
    }


    /**
     * 添加角色
     * @param role
     * @return
     */
    @PostMapping
    public Result add(@RequestBody Role role){
        log.info("添加角色");
        roleService.save(role);
        return Result.ok();
    }

    /**
     * 修改角色
     * @param role
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Role role){
        log.info("修改角色");
        roleService.updateById(role);
        return Result.ok();
    }


    /**
     * 删除角色
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable String id) {
        log.info("删除角色");
        return roleService.removeRole(id);
    }

    /**
     * 给角色分配权限
     * @param authorityDTO
     * @return
     * 给角色分配权限前先把该角色的权限都删了
     */
    @PostMapping("/authority")
    public Result authority(@RequestBody AuthorityDTO authorityDTO) {
        log.info("为角色分配权限");
        return roleService.gavePermission(authorityDTO);
    }

    /**
     * 获取角色权限
     * @param id
     * @return
     */
    @GetMapping("/getPermission/{id}")
    public Integer[] getPermission(@PathVariable Integer id) {
        Integer[] list = rolePermissionService.list(new LambdaQueryWrapper<RolePermission>().eq(RolePermission::getRoleId, id).select(RolePermission::getPermissionId))
                .stream().map(RolePermission::getPermissionId).toArray(Integer[]::new);
        return list;
    }

}
